package com.wxtwxt.ruralmall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.wxtwxt.ruralmall.common.to.SkuEsModel;
import com.wxtwxt.ruralmall.search.config.ElasticSearchConfig;
import com.wxtwxt.ruralmall.search.constant.EsConstant;
import com.wxtwxt.ruralmall.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Wxt
 * @create 2023-03-15 11:21
 */
@Service
@Slf4j
public class ProductSaveServiceImpl implements ProductSaveService {

    @Resource
    private RestHighLevelClient restHighLevelClient;

    @Override
    public Boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {
        // 1.为es创建索引，建立好映射关系
        // 2.将组装好的数据保存到es中
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModels) {
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(skuEsModel.getSkuId().toString());
            String jsonData = JSON.toJSONString(skuEsModel);
            indexRequest.source(jsonData, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, ElasticSearchConfig.COMMON_OPTIONS);
        // TODO 如果批量错误，进一步处理错误
        boolean flag = bulkResponse.hasFailures();
        if(flag) {
            List<String> collect = Arrays.stream(bulkResponse.getItems()).map(BulkItemResponse::getId).collect(Collectors.toList());
            log.error("商品上架错误：{}", collect);
        }
        return flag;
    }
}
